import React, { useEffect, useMemo, useRef } from 'react';
import { Chart } from '@antv/g2';
import Card from '../Card';



interface EnergyHistoryChartProps {
  energyHistory: any[]
}

const EnergyHistoryChart: React.FC<EnergyHistoryChartProps> = ({ energyHistory = [] }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<Chart | null>(null);

  const data = useMemo(() => {
    const list: any[] = []

    energyHistory?.forEach((item: any) => {

      list.push({
        '时间': item.weekDay,
        '数值': item.electricityConsumption,
        '类型': '电量'
      })

      list.push({
        '时间': item.weekDay,
        '数值': item.energySavingAmount,
        '类型': '金额'
      })

      list.push({
        '时间': item.weekDay,
        '数值': item.energySavingRatio * 100,
        '类型': '比例'
      })
    })

    return list
  }, [energyHistory])

  console.log('data', data)

  useEffect(() => {
    console.log('energyHistory', energyHistory)
    if (energyHistory?.length == 0 || !energyHistory) return

    const renderChart = () => {
      if (containerRef.current) {
        if (chartRef.current) {
          chartRef.current.destroy();
        }


        const chart = new Chart({
          container: containerRef.current,
          autoFit: true,
          theme: 'dark',
          // paddingRight: 120,
        });

        chart.coordinate({ transform: [{ type: 'transpose' }] });

        chart
          .interval()
          .data(data)
          // .transform({ type: 'sortX', reverse: true })
          .transform({ type: 'stackY' })
          .encode('x', '时间')
          .encode('y', '数值')
          .encode('color', '类型')
          // .axis('y', { labelFormatter: '.0%' })
        // .label({
        //   text: 'energySavingRatio',
        //   formatter: '.1%',
        //   textAlign: (d: any) => (+d.energySavingRatio > 0.008 ? 'right' : 'start'),
        //   fill: (d: any) => (+d.energySavingRatio > 0.008 ? '#fff' : '#000'),
        //   dx: (d: any) => (+d.energySavingRatio > 0.008 ? -5 : 5),
        // });
        chart.render();

        chartRef.current = chart;
      }
    };

    renderChart();

    const resizeObserver = new ResizeObserver(() => {
      renderChart();
    });

    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    return () => {
      resizeObserver.disconnect();
      if (chartRef.current) {
        chartRef.current.destroy();
      }
    };
  }, [energyHistory]);

  return <Card style={{ height: '50%', flexShrink: 0, flex: 1 }} title="节能历史" desc="（最近七天）（一天一条）电量/金额/比例堆叠" subTitle='The History of Energy Conservation'>
    <div ref={containerRef} className="chart-container" />
  </Card>;
};

export default EnergyHistoryChart;
